package view.cms
{
	import base.components.FileUpload;
	
	import business.AvatarDelegate;
	import business.BookDelegate;
	import business.CMSDelegate;
	import business.CardDelegate;
	import business.UserDelegate;
	
	import com.adobe.utils.ArrayUtil;
	
	import events.MyLogEvent;
	
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.ui.Keyboard;
	import flash.utils.Dictionary;
	
	import model.AppCons;
	import model.ModelLocator;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ICollectionView;
	import mx.collections.XMLListCollection;
	import mx.containers.Accordion;
	import mx.containers.Canvas;
	import mx.containers.HBox;
	import mx.containers.VBox;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.ComboBox;
	import mx.controls.DataGrid;
	import mx.controls.Image;
	import mx.controls.LinkButton;
	import mx.controls.TextInput;
	import mx.controls.Tree;
	import mx.core.IFlexDisplayObject;
	import mx.events.CloseEvent;
	import mx.events.ItemClickEvent;
	import mx.events.ListEvent;
	import mx.managers.PopUpManager;
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	
	import util.LogUtil;
	
	import view.cms.desktop.DrawingPage;
	import view.cms.desktop.DrawingShape;
	
	[Bindable]
	public class CMSSiteClass extends HBox
	{
		public var tempObj:Object = {};
		public var propertiesModel:ArrayCollection;
		
		public var siteTreeData:ICollectionView ;
		private var productModel:XML; 
		
		public var propertiesGrid:DataGrid;
		public var pages:Dictionary;
		public var queryTxt:TextInput;
		public var queryTxtBtn:Button;
		public var desktop:Canvas;
		
		public var siteTree:Tree;
		
		public var page:DrawingPage;
		
		public var delegate:CMSDelegate;
		
		public var pageVolume:int;
		
		public var previewArr:ArrayCollection;   // 预约时间
		
		private var avatarDelegate:AvatarDelegate;
		public var avatars:ArrayCollection;
		public var avatarPage:int;
		public var avatarPagecnt:int;
		public var avatarPageIndices:Array;
		
		private var userDelegate:UserDelegate;
		public var users:ArrayCollection;
		public var userPage:int;
		public var userPagecnt:int;
		public var userPageIndices:Array;
		
		private var cardDelegate:CardDelegate;
		public var cards:ArrayCollection;
		public var cardPage:int;
		public var cardPagecnt:int;
		public var cardPageIndices:Array;
		
		private var bookDelegate:BookDelegate;
		public var books:ArrayCollection;
		public var bookPage:int;
		public var bookPagecnt:int;
		public var bookPageIndices:Array;
		
		public var editor:Accordion;
		
		public var m:ModelLocator;
		public var resultArr:Array = [];
		
		public var img_uploadPic:Image;
		private var imgUploadName:String;
		private var uploadPicDisplay:IFlexDisplayObject;
		
		private var bInSearch:Boolean;      //是否在搜索
		private var searchPattern:String;   //搜索关键字
		private var searchType:String;      //在哪个字段搜索
		
		public var getPageFunction:Function;
		
		public var datas:*;	
		
		private var logId:String = '-1';	
		
		
		public function CMSSiteClass()
		{
			var loader:URLLoader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, xmlLoaded);
			loader.load(new URLRequest("http://www.aipai.com/app/admin/data/productmodel.xml"));
			this.page = null; 
			this.pages = new Dictionary();
			
			m = ModelLocator.getInstance();
			
			avatarDelegate = new AvatarDelegate(this);
			avatarDelegate.getConfigs();
			this.avatarPage = 0;
			
			userDelegate = new UserDelegate(this);
			this.userPage = 0;
			
			bookDelegate = new BookDelegate(this);
			this.bookPage = 0;
			
			cardDelegate = new CardDelegate(this);
			this.cardPage = 0;
			
			this.getPageFunction = this.getUserPage;
		}
		
		public function init():void
		{
			queryTxt.addEventListener(KeyboardEvent.KEY_DOWN, onKeyboardTxt);
			queryTxtBtn.addEventListener(MouseEvent.CLICK, onClickTxt);
		}
		
		private function onClickTxt(event:MouseEvent):void
		{
			selectQueryTxt(queryTxt.text);
		}
		private function onKeyboardTxt(event:KeyboardEvent):void
		{
			switch(event.charCode)
			{
				case Keyboard.ENTER:
					selectQueryTxt(queryTxt.text);
					break;
			}
		}
		
		private function selectQueryTxt(txt:String):void
		{
			if(queryTxt.text == null || queryTxt.text == "" || queryTxt.text.length == 0 || txt == "")
				return;
			
			
			// 先关闭所有节点
			for each(var item:XML in siteTree.dataProvider)
				siteTree.expandChildrenOf(item,false);
			
			var node:XMLList = Object(siteTreeData).source.page.(@name == txt);
			expandParents(node[0]);
			siteTree.selectedItem = node[0];
			var idx:int = siteTree.getItemIndex(node[0]);
			siteTree.scrollToIndex(idx);
			if(node)
			{
				changePage(int(node[0].@id));
			}
			
		}
		
		private function expandParents(node:XML):void 
		{
			if (node && !siteTree.isItemOpen(node)) {
				siteTree.expandItem(node, true);
				expandParents(node.parent());
			}
		}
		
		public function getConfigsResult(result:Object, token:Object = null):void
		{
			//			avatarDelegate.getAvatars(this.avatarPage);
			//			userDelegate.getUsers(this.userPage);
			//			bookDelegate.getBooksByAuditGood(this.bookPage);
			//			cardDelegate.getCardsByAuditGood(this.cardPage);
			result = result.result;
			this.pageVolume = result.pageVolume;
		}
		
		public function getAvatarsResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			this.avatars = new ArrayCollection(result.avatars);
			this.avatarPage = result.page;
			this.avatarPagecnt = result.pagecnt;
			
			this.makeAvatarPageIndices();			
			
			//			this.avatars.addEventListener(CollectionEvent.COLLECTION_CHANGE,onAvatarDataChanged);
		}
		
		public function getUsersResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			this.users = new ArrayCollection(result.users);
			this.userPage = result.page;
			this.userPagecnt = result.pagecnt;
			
			this.makeUserPageIndices();			
			
			//			this.users.addEventListener(CollectionEvent.COLLECTION_CHANGE,onUserDataChanged);
		}
		
		public function getBooksByAuditGoodResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			this.books = new ArrayCollection(result.books);
			this.bookPage = result.page;
			this.bookPagecnt = result.pagecnt;
			
			this.makeBookPageIndices();			
			
			//			this.books.addEventListener(CollectionEvent.COLLECTION_CHANGE,onBookDataChanged);
		}
		
		public function getCardsByAuditGoodResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			this.cards = new ArrayCollection(result.cards);
			this.cardPage = result.page;
			this.cardPagecnt = result.pagecnt;
			
			this.makeCardPageIndices();			
			
			//			this.cards.addEventListener(CollectionEvent.COLLECTION_CHANGE,onCardDataChanged);
		}
		
		/**
		 *  关联元素 
		 * 
		 */		
		public function switchToProduct():void
		{
			this.editor.selectedIndex = 1;
		}
		
		public function switchToDesktopByCard(productData:*):void
		{
			//this.editor.selectedIndex = 0;
			this.page.hookCardData(productData);
			datas = productData;
			
			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.show('魔法卡作品已经关联，需要给作者发送消息吗？',
				'提示',Alert.YES | Alert.NO,null,alertAuto,null,Alert.NO);				
		}
		
		public function alertAuto(event:CloseEvent):void
		{
			if(event.detail == Alert.YES)
			{
				//send message
				cardDelegate.sendMsgRecom(datas.bid, datas.title, datas.url);
				//var dd:* = datas;
			}
			this.editor.selectedIndex = 0;
		}
		
		public function alertUser(event:CloseEvent):void
		{
			if(event.detail == Alert.YES)
			{
				//send message
				userDelegate.sendMsgRecom(this.datas.bid);
			}
			this.editor.selectedIndex = 0;			
		}		
		
		public function switchToDesktopByBook(productData:*):void
		{
			//this.editor.selectedIndex = 0;
			this.page.hookBookData(productData);
			datas = productData;
			
			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.show('连环画作品已经关联，需要给作者发送消息吗？',
				'提示',Alert.YES | Alert.NO,null,alertAuto,null,Alert.NO);	
			
		}
		
		public function switchToDesktopByAvatar(productData:*):void
		{
			this.editor.selectedIndex = 0;
			this.page.hookAvatarData(productData);
		}
		
		public function switchToDesktopByUser(productData:*):void
		{
			//this.editor.selectedIndex = 0;
			this.page.hookUserData(productData);
			
			datas = productData;
			
			Alert.yesLabel = '确定';
			Alert.noLabel = '取消';
			Alert.show('用户已经关联，需要给用户发送消息吗？',
				'提示',Alert.YES | Alert.NO,null,alertUser,null,Alert.NO);				
			
		}
		
		private function makeBookPageIndices():void
		{
			var a:Array = new Array();
			a.push({bookPage:0,desc:'首页'});			
			a.push({bookPage:bookPage-1,desc:'前一页'});			
			a.push({bookPage:bookPage+1,desc:'后一页'});
			a.push({bookPage:bookPagecnt-1,desc:'尾页'});
			this.bookPageIndices = a;
		}
		
		private function makeCardPageIndices():void
		{
			var a:Array = new Array();
			a.push({cardPage:0,desc:'首页'});			
			a.push({cardPage:cardPage-1,desc:'前一页'});			
			a.push({cardPage:cardPage+1,desc:'后一页'});
			a.push({cardPage:cardPagecnt-1,desc:'尾页'});
			this.cardPageIndices = a;
		}
		
		private function makeUserPageIndices():void
		{
			var a:Array = new Array();
			a.push({userPage:0,desc:'首页'});			
			a.push({userPage:userPage-1,desc:'前一页'});			
			a.push({userPage:userPage+1,desc:'后一页'});
			a.push({userPage:userPagecnt-1,desc:'尾页'});
			this.userPageIndices = a;
		}
		
		private function makeAvatarPageIndices():void
		{
			var a:Array = new Array();
			a.push({avatarPage:0,desc:'首页'});			
			a.push({avatarPage:avatarPage-1,desc:'前一页'});			
			a.push({avatarPage:avatarPage+1,desc:'后一页'});
			a.push({avatarPage:avatarPagecnt-1,desc:'尾页'});
			this.avatarPageIndices = a;
		}
		
		public function getCardPage(page:int):void
		{
			if(this.bInSearch)
			{               
				cardDelegate.getCardsByAuditGoodBySearch(this.searchPattern, this.searchType, page);
			} else {
				cardDelegate.getCardsByAuditGood(page);
			}
		} 
		
		public function onSearchCard(type:String,pattern:String):void
		{
			this.bInSearch = true;
			this.searchType = type;
			this.searchPattern = pattern;
			this.getCardPage(0);
		}
		
		public function getCardsBySearchResult(result:Object, token:Object = null):void
		{
			this.getCardsByAuditGoodResult(result, token);
		}
		
		public function gotoCard(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.cardPage;
			this.getCardPage(page);
		}
		
		public function gotoCardPage(page:String):void
		{
			if (page.length>0)
			{
				this.getCardPage(int(page)-1);
			}
		}
		
		public function getBookPage(page:int):void
		{
			if(this.bInSearch)
			{               
				bookDelegate.getBooksByAuditGoodBySearch(this.searchPattern, this.searchType, page);
			} else {
				bookDelegate.getBooksByAuditGood(page);
			}
		} 
		
		public function onSearchBook(type:String,pattern:String):void
		{
			this.bInSearch = true;
			this.searchType = type;
			this.searchPattern = pattern;
			this.getBookPage(0);
		}
		
		public function getBooksBySearchResult(result:Object, token:Object = null):void
		{
			this.getBooksByAuditGoodResult(result, token);
		}
		
		public function sendMsgRecomResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if ( result.code )
			{
				var fault:Fault = new Fault('','消息发送失败');
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;
			}        	
		}
		
		public function gotoBook(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.bookPage;
			this.getBookPage(page);
		}
		
		public function gotoBookPage(page:String):void
		{
			if (page.length>0)
			{
				this.getBookPage(int(page)-1);
			}
		}        
		
		public function getAvatarPage(page:int):void
		{
			if(this.bInSearch)
			{               
				avatarDelegate.getAvatarsBySearch(this.searchPattern, this.searchType, page);
			} else {
				avatarDelegate.getAvatars(page);
			}
		} 
		
		public function onSearchAvatar(type:String,pattern:String):void
		{
			this.bInSearch = true;
			this.searchType = type;
			this.searchPattern = pattern;
			this.getAvatarPage(0);
		}
		
		public function getAvatarsBySearchResult(result:Object, token:Object = null):void
		{
			this.getAvatarsResult(result, token);
		}
		
		public function gotoAvatar(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.avatarPage;
			this.getAvatarPage(page);
		}
		
		public function gotoAvatarPage(page:String):void
		{
			if (page.length>0)
			{
				this.getAvatarPage(int(page)-1);
			}
		}
		
		public function getUserPage(page:int):void
		{
			if(this.bInSearch)
			{               
				userDelegate.getUsersBySearch(this.searchPattern, this.searchType, page);
			} else {
				userDelegate.getUsers(page);
			}
		} 
		
		public function onSearchUser(type:String,pattern:String):void
		{
			this.bInSearch = true;
			this.searchType = type;
			this.searchPattern = pattern;
			this.getUserPage(0);
		}
		
		public function getUsersBySearchResult(result:Object, token:Object = null):void
		{
			this.getUsersResult(result, token);
		}
		
		public function gotoUser(evt:MouseEvent):void
		{
			var page:int = LinkButton(evt.currentTarget).data.userPage;
			this.getUserPage(page);
		}
		
		public function gotoUserPage(page:String):void
		{
			if (page.length>0)
			{
				this.getUserPage(int(page)-1);
			}
		}
		
		private function xmlLoaded(evt:Event):void 
		{
			this.productModel = XML(evt.target.data);
			var s:XMLList = new XMLList() + productModel.site;
			siteTreeData = new XMLListCollection(s);
			delegate = new CMSDelegate(this);
			delegate.getPreviewDate();
		}
		
		public function getPreviewDateResult(result:Object, token:Object = null):void
		{
			result = result.result;
//			(result as Array).splice(0, 0,{time:"选择预约时间"}); 
			previewArr = new ArrayCollection(result as Array);
		}
		
		public function saveSitePageResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if ( result.code )
			{
				var fault:Fault = new Fault('',result.msg);
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;
			}
			if(!saveArr)
				return;
			var logObj:Object = {};
			logObj.uid = ModelLocator.getInstance().adminUserVO.id;
			logObj.username = ModelLocator.getInstance().adminUserVO.name;
			logObj.mid = AppCons.CMS;
			logObj.optSuccessd = '1';
			logObj.targetId = page.pid;
			logObj.record = "保存:pageId="+page.pid + "  ";
			for(var i:int=0; i<saveArr.length; i++)
			{
				//					logObj.record += "更新[id:"+a[i].id +",subId:" + a[i].subId +",subId2:"+ a[i].subId2+ ",pos:" + a[i].pos+ ",pos2:"+a[i].pos2 + ",action:"+a[i].action + "] ";
				var str:String = "\n"+saveArr[i].action+"[";
				for(var o:String in saveArr[i])
				{
					str += o+":"+saveArr[i][o] + ",  "	
				}
				logObj.record += str + "]\t\t";
			}
			LogUtil.getInstance().logDelegate.log(logObj);
			saveArr = null;
			
			flag = true;
			this.propertiesGrid.dataProvider = null;
			this.page.initAction();
			this.page.delArr = [];
		}
		
		private function goDelSitePage(event:MyLogEvent):void
		{
			
			event.target.removeEventListener(MyLogEvent.LOGREADY, goDelSitePage);
			delegate.delSitePages(event.record.a);  //del pages
		}
		
		public function publishSitePageResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if ( result.code )
			{
				var fault:Fault = new Fault('',result.msg);
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;
			}
			LogUtil.getInstance().setOptSuccessd(this.logId);
		}
		
		public function delSitePagesResult(result:Object, token:Object = null):void
		{
			addSitePages();
			
			result = result.result;
			this.page.delArr = [];
			if ( result.code )
			{
				var fault:Fault = new Fault('',result.msg);
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;
			}
		}
		
		public function loadSitePageResult(result:Object, token:Object = null):void
		{
			result = result.result;
			
			if ( result.code )
			{
				var fault:Fault = new Fault('',result.msg);
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;
			}
			
			if ( this.page && result.pid == this.page.pid ) 
			{
				this.page.inport(result.items);
				this.page.loaded = true;
			}
			
		}
		
		public function fault(error:FaultEvent,token:Object = null):void
		{
			Alert.show(error.fault.faultString,'error');
		}
		
		private function delSelectedSitePage(event:CloseEvent):void
		{
			if (event.detail==Alert.YES)
			{ 
				page.deleteSelectedChildren();
			}
		}
		
		/**
		 *  更新、删除根据id操作 
		 * add：    id值没空的对象即为增加
		 * */
		private var flag:Boolean = true;
		private var saveArr:Array;
		private function addSitePages():void
		{
			if(flag == false)return;
			saveArr = this.page.export();
			if(page.delArr.length>0)
				saveArr = saveArr.concat(page.delArr);
			if(saveArr.length==0)return;
			
			//				delegate.saveSitePage(a,this.page.pid);
			flag = false;
			delegate.saveSitePage(saveArr, page.pid);
			
			//			LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goSaveSitePage);	
			//			LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.CMS, LogUtil.SAVE, obj);
			
			//make recommend res
			if(this.page.pid == 10003)
			{
				makeRequest("http://so.aipai.com/apps/makeRecommends.php");
			}
			else if(this.page.pid == 30000)  //del ad res
			{
				makeRequest('http://so.aipai.com/apps/getRes.php?delTmp=1');
				makeRequest('http://so.aipai.com/apps/getResNew.php');
				//makeRequest('http://so.aipai.com/apps/getResJs.php');
			}
		}
		
		public function clickHandler(event:ItemClickEvent):void 
		{
			if ( !m.lock && this.page && event.index == 0 ) // add sub area
			{
				this.page.addItem(null,true);
			}
			else if ( !m.lock && this.page && event.index == 1 ) // add iteme
			{
				this.page.addItem(null,false);
			}
			else if( this.page && event.index == 2 )  //delete item
			{
				if(page.selected==null || page.manipulator==null)
				{
					Alert.show("请先选择需要删除的元素!");
					return;
				}
				Alert.show('确认删除所选元素吗？',
					'提示',Alert.YES | Alert.NO,null,delSelectedSitePage,null,Alert.NO);
			}
			else if ( this.page && event.index == 3 ) // save page
			{
				
				addSitePages();
				//				delSelectPages();
				
			}
			else if ( this.page && event.index == 4 ) // publish data
			{
				Alert.show('确认发布？',
					'提示',Alert.YES | Alert.NO,null,surePublishSitePage,null,Alert.NO);
			}
		}
		
		private function surePublishSitePage(event:CloseEvent):void 
		{
			if (event.detail==Alert.YES)
			{ 
				LogUtil.getInstance().addEventListener(MyLogEvent.LOGREADY, goPublishSitePage);
				LogUtil.getInstance().log(ModelLocator.getInstance().adminUserVO.id, ModelLocator.getInstance().adminUserVO.name, AppCons.CMS, LogUtil.PUBLISH, String(this.page.pid));
				//delegate.publishSitePage(this.page.pid);
			}
		}
		
		private function makeRequest(url:String):void
		{
			var urlReq:URLRequest = new URLRequest(url);
			var urlLoader:URLLoader = new URLLoader();	
			urlLoader.load(urlReq);      
		}
		
		private function goPublishSitePage(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goPublishSitePage);
			this.logId = event.logId;
			delegate.publishSitePage(event.record);         	
		}
		
		private function goSaveSitePage(event:MyLogEvent):void
		{
			event.target.removeEventListener(MyLogEvent.LOGREADY, goSaveSitePage);
			this.logId = event.logId;
			delegate.saveSitePage(event.record.a, event.record.pid);  
			
		}
		
		public function sizeClickHandler(event:ItemClickEvent):void 
		{
			if ( this.page && event.index == 0 ) // enlarge
			{
				this.page.height += 20;
			}
			else if ( this.page && event.index == 1 ) // cut
			{
				this.page.height -= 20;
			}
		}
		
		public function onTreeChanged(event:ListEvent):void 
		{
			this.changePage(XML(siteTree.selectedItem).@id);			
		}
		
		private function changePage(pid:int):void
		{
			if ( pid == -1 )
				return;
			
			var p:DrawingPage = this.pages[pid];
			
			if ( !p ) // first time
			{
				p = new DrawingPage(this.desktop.width,this.desktop.height);
				p.loaded = false;
				this.pages[pid] = p;
				p.pid = pid;
				delegate.loadSitePage(pid);
			}
			
			if ( page && page == p )
				return;
			
			if ( page && this.desktop.contains(page) )
			{
				this.desktop.removeChild(page);
			}
			
			page = p;
			this.desktop.addChildAt(p, 0);
			
			//			BindingUtils.bindProperty(this.desktop,'height',page,'height');
		}
		
		public var selectShape:DrawingShape;
		public function onElementSelected(element:DrawingShape):void
		{
			this.propertiesGrid.dataProvider = element.properties;
			selectShape = element;
		}        
		
		
		public var propertiesArr:Array;
		
		public var queryTimeArr:ArrayCollection;
		
		
//		public function queryBookInfo(event:MouseEvent):void
//		{
//			delegate.loadItemInfo(queryTimeBox.selectedItem.id);
//		}
		
		public function loadItemInfoResult(result:Object, token:Object = null):void
		{
			result = result.result;
			if ( result.code )
			{
				var fault:Fault = new Fault('',result.msg);
				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
				this.fault(error);
				return;
			}
			if(result.data)
			{
				var arr:Object = result.data;
				arr["action"] = "";  //已经有预约的信息，action为upate
				for (var temp:String in arr )
				{
					selectShape.setValue(temp, arr[temp]);
				}
			}
		}
		
//		public function savePreview(event:MouseEvent):void
//		{
//			if(page.selected == null)
//			{
//				Alert.show("请先选择元素，再进行预约！");
//				return;
//			}
//			else if(oderTimeBox.selectedIndex == 0)
//			{
//				Alert.show("当天的元素不需要预约！");
//				return;
//			}
//			var tempArr:Array = XMLListCollection(propertiesGrid.dataProvider).toArray();
//			var obj:Object = {};
//			propertiesArr = [];
//			for(var n:int=0; n<tempArr.length; n++)
//			{
//				obj[tempArr[n].@label] = String(tempArr[n].@value); 
//			}
//			obj["time"] = oderTimeBox.selectedItem.time;
//			obj["layout"] = page.selected.getLayout();
//		 	propertiesArr.push(obj); 
//			if(obj["action"] == "update")			
//			{
//				Alert.show("请确认您将更新所选元素 " + oderTimeBox.selectedItem.time + " 的预约信息？",'提示',Alert.YES | Alert.NO,null,sureSaveSitePage,null,Alert.NO);
//			}
//			else  if(obj["action"] == "add")
//			{
//				Alert.show("请确认您将添加所选元素 " + oderTimeBox.selectedItem.time + " 的预约信息？",'提示',Alert.YES | Alert.NO,null,sureSaveSitePage,null,Alert.NO);
//			}
//		}
		
		
//		private static var type:String = "";
//		private var saveItem:Object;
//		private function sureSaveSitePage(event:CloseEvent):void
//		{
//			if (event.detail==Alert.YES)
//			{ 
//				type = "saveOneItem";
//				var a:Array = propertiesArr; 
//				var logObj:Object = {};
//				logObj.uid = ModelLocator.getInstance().adminUserVO.id;
//				logObj.username = ModelLocator.getInstance().adminUserVO.name;
//				logObj.mid = AppCons.CMS;
//				logObj.optSuccessd = '1';
//				logObj.record = "保存:pageId="+page.pid + "  ";
//				saveItem =
//				{
//					pageId:a[0]["pageId"],
//					pos:a[0]["pos"],
//					subId:a[0]["subId"]
//				};
//				logObj.record += "[subId:" + a[0]["subId"] + ",pos:" + a[0]["pos"] + ",action:"+ a[0]["action"] + "] ";
//				LogUtil.getInstance().logDelegate.log(logObj);
//				delegate.saveSitePage(a, page.pid);
//			}
//		}
		
//		public function queryPreviewInfo(event:MouseEvent):void
//		{
//		}
		
		/**
		 * 根据用户信息查询出当前选择对象的 预约信息
		 * @param event
		 * 
		 */		
//		public function changeOrderInfo(event:Event):void
//		{
//			var element:DrawingShape = page.selected;
//			if(element == null)
//			{
//				oderTimeBox.selectedIndex = 0;			
//				Alert.show("请先选择元素，再查询预约情况！");
//				return;
//			}
//			if(queryTimeBox.selectedItem.time == "选择预约时间")
//			{
//				onElementSelected(page.selected);
//				return;
//			}
//			delegate.loadBookingInfo(int(element.getValue("pageId")), int(element.getValue("subId")),
//				int(element.getValue("pos")));
//		}
		
//		public function loadBookingInfoResult(result:Object, token:Object = null):void
//		{
//			result = result.result;
//			if ( result.code )
//			{
//				var fault:Fault = new Fault('',result.msg);
//				var error:FaultEvent = new FaultEvent('fault',false,true,fault);
//				this.fault(error);
//				return;
//			}
//			var xml:XML = <root/>
//			if(result.data == null)
//			{
//				Alert.show("您选择的元素没有预约该天的信息, 可以预约！");
//				var tempArr:Array = XMLListCollection(propertiesGrid.dataProvider).toArray();
//				var obj:Object = {};
//				for(var n:int=0; n<tempArr.length; n++)
//				{
//					obj[tempArr[n].@label] = String(tempArr[n].@value); 
//				}
//				// 没有预约的信息id 为空，action为add
//				obj["id"] = "";
//				obj["action"] = "add";
//				obj["time"] = oderTimeBox.selectedItem.time;
//				for (var s:String in obj )
//				{
//					xml.appendChild(<prop label={s} value={obj[s]} />);
//				}
//				this.propertiesGrid.dataProvider = new XMLListCollection(xml.prop);
//				return;				
//			}
//			else 
//			{
//				var arr:Object = result.data;
//				arr["action"] = "update";  //已经有预约的信息，action为upate
//				for (var temp:String in arr )
//				{
//					xml.appendChild(<prop label={temp} value={arr[temp]} />);
//				}
//				this.propertiesGrid.dataProvider = new XMLListCollection(xml.prop);
//			}
//		}
		
		public function onUploadPic():void
		{   
			if (this.page.selected)
			{
				var pageId:int = this.page.selected.propertiesXML.prop.(@label=='pageId').@value;	
				var subId:int = this.page.selected.propertiesXML.prop.(@label=='subId').@value;
				var pos:int = this.page.selected.propertiesXML.prop.(@label=='pos').@value;
			}
			
			this.uploadPicDisplay = PopUpManager.createPopUp(this,FileUpload,true);
			PopUpManager.bringToFront(this.uploadPicDisplay);
			PopUpManager.centerPopUp(this.uploadPicDisplay);
			
			FileUpload(this.uploadPicDisplay).uploadUrl = 'http://www.aipai.com/app/admin/service/upload/uploadPic.php';
			
			FileUpload(this.uploadPicDisplay).variables.pageId = pageId;
			FileUpload(this.uploadPicDisplay).variables.subId = subId;
			FileUpload(this.uploadPicDisplay).variables.pos = pos;
			
			FileUpload(this.uploadPicDisplay).addEventListener('uploadComplete',onUploadComplete);
			FileUpload(this.uploadPicDisplay).addEventListener('uploadDataComplete',onUploadDataComplete);
			FileUpload(this.uploadPicDisplay).addEventListener('uploadIOError',function(evt:Event):void{Alert.show('IO错误!', '提示')});
			FileUpload(this.uploadPicDisplay).addEventListener('uploadSecurityError',function(evt:Event):void{Alert.show('安全错误!', '提示')});     	
		}
		
		public function onConfirmPic():void
		{
			if (this.page.selected)
			{
				var pageId:int = this.page.selected.propertiesXML.prop.(@label=='pageId').@value;	
				var subId:int = this.page.selected.propertiesXML.prop.(@label=='subId').@value;
				var pos:int = this.page.selected.propertiesXML.prop.(@label=='pos').@value;
			}
			
			//确认图片关联
			var url:String = 'http://www.aipai.com/app/admin/service/upload/uploadPic.php'
				+'?action=comfirm&pageId='+pageId+'&subId='+subId+'&pos='+pos
				+'&imgtmp='+this.imgUploadName;
			
			var myRequest:URLRequest = new URLRequest(url);
			
			var myURLLoader:URLLoader = new URLLoader();
			myURLLoader.dataFormat = URLLoaderDataFormat.TEXT;
			
			myURLLoader.addEventListener(Event.COMPLETE, completeHandler);
			//myURLLoader.addEventListener(Event.OPEN, openHandler);
			//myURLLoader.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			//myURLLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			//myURLLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			//myURLLoader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			
			try {
				myURLLoader.load(myRequest);
			} catch (error:Error) {
				trace("load info xml failed!");
			}        		
		}
		
		private function completeHandler(event:Event):void 
		{
			var loader:URLLoader = URLLoader(event.target);
			trace("info.xml load completeHandler: " + loader.data);
			
			var result:XML = new XML(loader.data);
			
			Alert.show('图片关联成功!', '提示');
			var imageSrc:String = String(result.file_name_www); 
			if( imageSrc != null && imageSrc !="")
				this.page.selected.setValue('imageSrc',imageSrc);
			this.page.updateSitePageAction();
		}
		
		private function onUploadComplete(evt:Event):void
		{
			//Alert.show('文件上传成功!', '提示');
			PopUpManager.removePopUp(this.uploadPicDisplay);
		}
		
		private function onUploadDataComplete(event:DataEvent):void
		{
			var result:XML = new XML(event.data);
			
			this.imgUploadName = result.file_name;
			
			img_uploadPic.source = result.file_name_www+"?sss="+Math.random().toString();
			img_uploadPic.load();
		}
		
		public function goBack():void
		{
			this.editor.selectedIndex = 0;
		}
		
		public function onReset():void
		{
			this.bInSearch = false;
			this.getPageFunction(0);
		}
	}
}